package com.lbm.baseclass.session;

import java.net.URLEncoder;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.lbm.baseclass.constants.Consts;
import com.lbm.baseclass.utils.Eryptogram;
import com.lbm.business.web.controller.LoginController;

/**
 * <p> Title: 判断会话是否失效，否则重新登录</p>
 * <p> Description:</p>
 * <p> Copyright: Copyright (c) 2011 </p>
 * <p> Company:aft.co.,ltd </p>
 *
 * @author zhujw
 * @version 1.0
 */
public class SessionInterceptor extends HandlerInterceptorAdapter {
	protected static Logger log = Logger.getLogger(SessionInterceptor.class);
	@SuppressWarnings("unused")
	private String redirectTo;
	
	@SuppressWarnings("unchecked")
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession(false);
		
		if (handler.getClass().equals(LoginController.class)
				|| handler
						.getClass()
						.getName()
						.equals("com.ssa.business.web.controller.LoginController")
				|| handler
						.getClass()
						.getName()
						.equals("com.ssa.business.web.controller.LoginController")) {
			log.info("正常登录");
			return true;
		}
		//判断参数中是否有传sessionId,解决FLASH上传中的会话丢失BUG
		String existSession = request.getParameter("jsessionid");
		if (existSession!=null&&existSession!="") session = LBMSessionListener.getSession(existSession);
		if (session == null || session.getAttribute(Consts.USER_INFO) == null) {
			log.info("会话失效或未登陆，跳转到登陆页面");
			StringBuffer url = request.getRequestURL();
			Enumeration<String> names = request.getParameterNames();
			url.append("?");
			while (names.hasMoreElements()) {
				String name = names.nextElement();
				url.append(name);
				url.append("=");
				url.append(request.getParameter(name) + "&");
			}
			String u = url.substring(0, url.length() - 1);
			String encrypt = Eryptogram.encrypt(u);
			String msg = URLEncoder.encode(URLEncoder.encode("您的会话已失效，请重新登陆", "UTF-8"), "UTF-8");
			String urlStr = "http://" + request.getServerName() + ":" + request.getServerPort() + "/"+request.getContextPath()+"/login.jsp?url="+encrypt + "&msg=" + msg;
			response.sendRedirect(urlStr);
			return false;
		}
		
		return super.preHandle(request, response, handler);
	}

	public void setRedirectTo(String redirectTo) {
		this.redirectTo = redirectTo;
	}

}
